package com.ewei.web.authority.shiro.stateless;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ewei.web.authority.annotations.SessionUpdate;
import com.ewei.web.authority.utils.TokenUtils;
public class CookieInterceptor extends HandlerInterceptorAdapter{
	@Resource
	private TokenUtils tokenUtil;
	@Value("${cookie.domain}")
	private String domain;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
//		System.out.println("进入springMVC拦截器");
		Subject subject = SecurityUtils.getSubject();
		if(handler instanceof HandlerMethod){
			HandlerMethod method = (HandlerMethod)handler;
			if(!method.getMethod().isAnnotationPresent(SessionUpdate.class)){//排除改变会话的方法
				if(null!=subject.getPrincipal()){//判断无状态登陆是否成功
					addCookie((String) subject.getPrincipal(),request,response);//更新Cookie
				}
			}
		}
		return true;
	}
	@SuppressWarnings("static-access")
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		if(handler instanceof HandlerMethod){
			HandlerMethod method = (HandlerMethod)handler;
			if(method.getMethod().isAnnotationPresent(SessionUpdate.class)){//只对改变会话方法拦截
				if(null!=subject.getPrincipal()){//判断是否登录成功
						addCookie((String) subject.getPrincipal(),request,response);//生成Cookie
				}else{//否则生成空Cookie
					Cookie cookie = new SimpleCookie();
					cookie.setName(tokenUtil.COOKIE_NAME);
					cookie.setHttpOnly(true);
					cookie.setMaxAge(60*60);
					cookie.setValue("");
					cookie.setPath("/");
					if(null!=domain&&!"".equals(domain)){
						cookie.setDomain(domain);
					}
					cookie.saveTo(request,response);
					System.out.println("F2");
				}
			}
		}
	}
	@SuppressWarnings("static-access")
	private void addCookie(String username,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String auth = tokenUtil.generateAuth(username);
		String token = tokenUtil.generateToken(username);
		Cookie cookie = new SimpleCookie();
		cookie.setName(tokenUtil.COOKIE_NAME);
		cookie.setHttpOnly(true);
		cookie.setMaxAge(60*60);
		cookie.setValue(URLEncoder.encode(token+","+auth,"UTF-8"));//对Cookie的值编码
		cookie.setPath("/");
		if(null!=domain&&!"".equals(domain)){
			cookie.setDomain(domain);
		}
		cookie.saveTo(request,response);
	}
}
